home *** CD-ROM | disk | FTP | other *** search
/ Enter 2006 September / Enter 09 2006.iso / Internet / SpamExperts Home 1.1 / SpamExperts Home.exe / lib / spamexperts.modules / spambayes / Dibbler.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2006-07-14  |  28.8 KB  |  794 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.4)
  3.  
  4. '''
  5. *Introduction*
  6.  
  7. Dibbler is a Python web application framework.  It lets you create web-based
  8. applications by writing independent plug-in modules that don\'t require any
  9. networking code.  Dibbler takes care of the HTTP side of things, leaving you
  10. to write the application code.
  11.  
  12.  
  13. *Plugins and Methlets*
  14.  
  15. Dibbler uses a system of plugins to implement the application logic.  Each
  16. page maps to a \'methlet\', which is a method of a plugin object that serves
  17. that page, and is named after the page it serves.  The address
  18. `http://server/spam` calls the methlet `onSpam`.  `onHome` is a reserved
  19. methlet name for the home page, `http://server/`.  For resources that need a
  20. file extension (eg. images) you can use a URL such as `http://server/eggs.gif`
  21. to map to the `onEggsGif` methlet.  All the registered plugins are searched
  22. for the appropriate methlet, so you can combine multiple plugins to build
  23. your application.
  24.  
  25. A methlet needs to call `self.writeOKHeaders(\'text/html\')` followed by
  26. `self.write(content)`.  You can pass whatever content-type you like to
  27. `writeOKHeaders`, so serving images, PDFs, etc. is no problem.  If a methlet
  28. wants to return an HTTP error code, it should call (for example)
  29. `self.writeError(403, "Forbidden")` instead of `writeOKHeaders`
  30. and `write`.  If it wants to write its own headers (for instance to return
  31. a redirect) it can simply call `write` with the full HTTP response.
  32.  
  33. If a methlet raises an exception, it is automatically turned into a "500
  34. Server Error" page with a full traceback in it.
  35.  
  36.  
  37. *Parameters*
  38.  
  39. Methlets can take parameters, the values of which are taken from form
  40. parameters submitted by the browser.  So if your form says
  41. `<form action=\'subscribe\'><input type="text" name="email"/> ...` then your
  42. methlet should look like `def onSubscribe(self, email=None)`.  It\'s good
  43. practice to give all the parameters default values, in case the user navigates
  44. to that URL without submitting a form, or submits the form without filling in
  45. any parameters.  If you have lots of parameters, or their names are determined
  46. at runtime, you can define your methlet like this:
  47. `def onComplex(self, **params)` to get a dictionary of parameters.
  48.  
  49.  
  50. *Example*
  51.  
  52. Here\'s a web application server that serves a calendar for a given year:
  53.  
  54. >>> import Dibbler, calendar
  55. >>> class Calendar(Dibbler.HTTPPlugin):
  56. ...     _form = \'\'\'<html><body><h3>Calendar Server</h3>
  57. ...                <form action=\'/\'>
  58. ...                Year: <input type=\'text\' name=\'year\' size=\'4\'>
  59. ...                <input type=\'submit\' value=\'Go\'></form>
  60. ...                <pre>%s</pre></body></html>\'\'\'
  61. ...
  62. ...     def onHome(self, year=None):
  63. ...         if year:
  64. ...             result = calendar.calendar(int(year))
  65. ...         else:
  66. ...             result = ""
  67. ...         self.writeOKHeaders(\'text/html\')
  68. ...         self.write(self._form % result)
  69. ...
  70. >>> httpServer = Dibbler.HTTPServer(8888)
  71. >>> httpServer.register(Calendar())
  72. >>> Dibbler.run(launchBrowser=True)
  73.  
  74. Your browser will start, and you can ask for a calendar for the year of
  75. your choice.  If you don\'t want to start the browser automatically, just call
  76. `run()` with no arguments - the application is available at
  77. http://localhost:8888/ .  You\'ll have to kill the server manually because it
  78. provides no way to stop it; a real application would have some kind of
  79. \'shutdown\' methlet that called `sys.exit()`.
  80.  
  81. By combining Dibbler with an HTML manipulation library like
  82. PyMeld (shameless plug - see http://entrian.com/PyMeld for details) you can
  83. keep the HTML and Python code separate.
  84.  
  85.  
  86. *Building applications*
  87.  
  88. You can run several plugins together like this:
  89.  
  90. >>> httpServer = Dibbler.HTTPServer()
  91. >>> httpServer.register(plugin1, plugin2, plugin3)
  92. >>> Dibbler.run()
  93.  
  94. ...so many plugin objects, each implementing a different set of pages,
  95. can cooperate to implement a web application.  See also the `HTTPServer`
  96. documentation for details of how to run multiple `Dibbler` environments
  97. simultaneously in different threads.
  98.  
  99.  
  100. *Controlling connections*
  101.  
  102. There are times when your code needs to be informed the moment an incoming
  103. connection is received, before any HTTP conversation begins.  For instance,
  104. you might want to only accept connections from `localhost` for security
  105. reasons.  If this is the case, your plugin should implement the
  106. `onIncomingConnection` method.  This will be passed the incoming socket
  107. before any reads or writes have taken place, and should return True to allow
  108. the connection through or False to reject it.  Here\'s an implementation of
  109. the `localhost`-only idea:
  110.  
  111. >>> def onIncomingConnection(self, clientSocket):
  112. >>>     return clientSocket.getpeername()[0] == clientSocket.getsockname()[0]
  113.  
  114.  
  115. *Advanced usage: Dibbler Contexts*
  116.  
  117. If you want to run several independent Dibbler environments (in different
  118. threads for example) then each should use its own `Context`.  Normally
  119. you\'d say something like:
  120.  
  121. >>> httpServer = Dibbler.HTTPServer()
  122. >>> httpServer.register(MyPlugin())
  123. >>> Dibbler.run()
  124.  
  125. but that\'s only safe to do from one thread.  Instead, you can say:
  126.  
  127. >>> myContext = Dibbler.Context()
  128. >>> httpServer = Dibbler.HTTPServer(context=myContext)
  129. >>> httpServer.register(MyPlugin())
  130. >>> Dibbler.run(myContext)
  131.  
  132. in as many threads as you like.
  133.  
  134.  
  135. *Dibbler and asyncore*
  136.  
  137. If this section means nothing to you, you can safely ignore it.
  138.  
  139. Dibbler is built on top of Python\'s asyncore library, which means that it
  140. integrates into other asyncore-based applications, and you can write other
  141. asyncore-based components and run them as part of the same application.
  142.  
  143. By default, Dibbler uses the default asyncore socket map.  This means that
  144. `Dibbler.run()` also runs your asyncore-based components, provided they\'re
  145. using the default socket map.  If you want to tell Dibbler to use a
  146. different socket map, either to co-exist with other asyncore-based components
  147. using that map or to insulate Dibbler from such components by using a
  148. different map, you need to use a `Dibbler.Context`.  If you\'re using your own
  149. socket map, give it to the context: `context = Dibbler.Context(myMap)`.  If
  150. you want Dibbler to use its own map: `context = Dibbler.Context({})`.
  151.  
  152. You can either call `Dibbler.run(context)` to run the async loop, or call
  153. `asyncore.loop()` directly - the only difference is that the former has a
  154. few more options, like launching the web browser automatically.
  155.  
  156.  
  157. *Self-test*
  158.  
  159. Running `Dibbler.py` directly as a script runs the example calendar server
  160. plus a self-test.
  161. '''
  162. __author__ = 'Richie Hindle <richie@entrian.com>'
  163. __credits__ = 'Tim Stone'
  164.  
  165. try:
  166.     import cStringIO as StringIO
  167. except ImportError:
  168.     import StringIO
  169.  
  170. import os
  171. import sys
  172. import re
  173. import time
  174. import traceback
  175. import md5
  176. import base64
  177. import socket
  178. import asyncore
  179. import asynchat
  180. import cgi
  181. import urlparse
  182. import webbrowser
  183.  
  184. try:
  185.     (True, False)
  186. except NameError:
  187.     (True, False) = (1, 0)
  188.  
  189.  
  190. try:
  191.     ''.rstrip('abc')
  192. except TypeError:
  193.     RSTRIP_CHARS_AVAILABLE = False
  194.  
  195. RSTRIP_CHARS_AVAILABLE = True
  196.  
  197. class BrighterAsyncChat(asynchat.async_chat):
  198.     """An asynchat.async_chat that doesn't give spurious warnings on
  199.     receiving an incoming connection, lets SystemExit cause an exit, can
  200.     flush its output, and will correctly remove itself from a non-default
  201.     socket map on `close()`."""
  202.     
  203.     def __init__(self, conn = None, map = None):
  204.         '''See `asynchat.async_chat`.'''
  205.         asynchat.async_chat.__init__(self, conn)
  206.         self._BrighterAsyncChat__map = map
  207.         self._closed = False
  208.  
  209.     
  210.     def handle_connect(self):
  211.         '''Suppresses the asyncore "unhandled connect event" warning.'''
  212.         pass
  213.  
  214.     
  215.     def handle_error(self):
  216.         '''Let SystemExit cause an exit.'''
  217.         (type, v, t) = sys.exc_info()
  218.         if type == SystemExit:
  219.             raise 
  220.         else:
  221.             asynchat.async_chat.handle_error(self)
  222.  
  223.     
  224.     def flush(self):
  225.         '''Flush everything in the output buffer.'''
  226.         while (self.producer_fifo or self.ac_out_buffer) and not (self._closed):
  227.             self.initiate_send()
  228.  
  229.     
  230.     def close(self):
  231.         '''Remove this object from the correct socket map.'''
  232.         self._closed = True
  233.         self.del_channel(self._BrighterAsyncChat__map)
  234.         self.socket.close()
  235.  
  236.  
  237.  
  238. class Context:
  239.     '''See the main documentation for details of `Dibbler.Context`.'''
  240.     
  241.     def __init__(self, asyncMap = asyncore.socket_map):
  242.         self._HTTPPort = None
  243.         self._map = asyncMap
  244.  
  245.     
  246.     def pop(self, key):
  247.         return self._map.pop(key)
  248.  
  249.     
  250.     def keys(self):
  251.         return self._map.keys()
  252.  
  253.     
  254.     def __len__(self):
  255.         return len(self._map)
  256.  
  257.  
  258. _defaultContext = Context()
  259.  
  260. class Listener(asyncore.dispatcher):
  261.     '''Generic listener class used by all the different types of server.
  262.     Listens for incoming socket connections and calls a factory function
  263.     to create handlers for them.'''
  264.     
  265.     def __init__(self, port, factory, factoryArgs, socketMap = _defaultContext._map):
  266.         """Creates a listener object, which will listen for incoming
  267.         connections when Dibbler.run is called:
  268.  
  269.          o port: The TCP/IP (address, port) to listen on. Usually '' -
  270.            meaning bind to all IP addresses that the machine has - will be
  271.            passed as the address.  If `port` is just an int, an address of
  272.            '' will be assumed.
  273.  
  274.          o factory: The function to call to create a handler (can be a class
  275.            name).
  276.  
  277.          o factoryArgs: The arguments to pass to the handler factory.  For
  278.            proper context support, this should include a `context` argument
  279.            (or a `socketMap` argument for pure asyncore listeners).  The
  280.            incoming socket will be prepended to this list, and passed as the
  281.            first argument.  See `HTTPServer` for an example.
  282.  
  283.          o socketMap: Optional.  The asyncore socket map to use.  If you're
  284.            using a `Dibbler.Context`, pass context._map.
  285.  
  286.         See `HTTPServer` for an example `Listener` - it's a good deal smaller
  287.         than this description!"""
  288.         asyncore.dispatcher.__init__(self, map = socketMap)
  289.         self.socketMap = socketMap
  290.         self.factory = factory
  291.         self.factoryArgs = factoryArgs
  292.         s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  293.         s.setblocking(False)
  294.         self.set_socket(s, self.socketMap)
  295.         self.set_reuse_addr()
  296.         if type(port) != type(()):
  297.             port = ('', port)
  298.         
  299.         self.bind(port)
  300.         self.listen(5)
  301.  
  302.     
  303.     def handle_accept(self):
  304.         '''Asyncore override.'''
  305.         result = self.accept()
  306.         if result:
  307.             (clientSocket, clientAddress) = result
  308.             args = [
  309.                 clientSocket] + list(self.factoryArgs)
  310.             self.factory(*args)
  311.         
  312.  
  313.  
  314.  
  315. class HTTPServer(Listener):
  316.     """A web server with which you can register `HTTPPlugin`s to serve up
  317.     your content - see `HTTPPlugin` for detailed documentation and examples.
  318.  
  319.     `port` specifies the TCP/IP (address, port) on which to run, defaulting
  320.     to ('', 80).
  321.  
  322.     `context` optionally specifies a `Dibbler.Context` for the server.
  323.     """
  324.     NO_AUTHENTICATION = 'None'
  325.     BASIC_AUTHENTICATION = 'Basic'
  326.     DIGEST_AUTHENTICATION = 'Digest'
  327.     
  328.     def __init__(self, port = ('', 80), context = _defaultContext):
  329.         '''Create an `HTTPServer` for the given port.'''
  330.         Listener.__init__(self, port, _HTTPHandler, (self, context), context._map)
  331.         self._plugins = []
  332.         
  333.         try:
  334.             context._HTTPPort = port[1]
  335.         except TypeError:
  336.             context._HTTPPort = port
  337.  
  338.  
  339.     
  340.     def register(self, *plugins):
  341.         '''Registers one or more `HTTPPlugin`-derived objects with the
  342.         server.'''
  343.         for plugin in plugins:
  344.             self._plugins.append(plugin)
  345.         
  346.  
  347.     
  348.     def requestAuthenticationMode(self):
  349.         '''Override: HTTP Authentication. It should return a value among
  350.         NO_AUTHENTICATION, BASIC_AUTHENTICATION and DIGEST_AUTHENTICATION.
  351.         The two last values will force HTTP authentication respectively
  352.         through Base64 and MD5 encodings.'''
  353.         return self.NO_AUTHENTICATION
  354.  
  355.     
  356.     def isValidUser(self, name, password):
  357.         '''Override: Return True for authorized logins.'''
  358.         return True
  359.  
  360.     
  361.     def getPasswordForUser(self, name):
  362.         '''Override: Return the password associated to the specified user
  363.         name.'''
  364.         return ''
  365.  
  366.     
  367.     def getRealm(self):
  368.         '''Override: Specify the HTTP authentication realm.'''
  369.         return 'Dibbler application server'
  370.  
  371.     
  372.     def getCancelMessage(self):
  373.         '''Override: Specify the cancel message for an HTTP Authentication.'''
  374.         return 'You must log in.'
  375.  
  376.  
  377.  
  378. class _HTTPHandler(BrighterAsyncChat):
  379.     '''This is a helper for the HTTP server class - one of these is created
  380.     for each incoming request, and does the job of decoding the HTTP traffic
  381.     and driving the plugins.'''
  382.     _login_splitter = re.compile('([a-zA-Z]+)=(".*?"|.*?),?')
  383.     
  384.     def __init__(self, clientSocket, server, context):
  385.         BrighterAsyncChat.__init__(self, map = context._map)
  386.         BrighterAsyncChat.set_socket(self, clientSocket, context._map)
  387.         self._context = context
  388.         self._server = server
  389.         self._request = ''
  390.         self.set_terminator('\r\n\r\n')
  391.         self._bufferedHeaders = []
  392.         self._headersWritten = False
  393.         for plugin in self._server._plugins:
  394.             if not plugin.onIncomingConnection(clientSocket):
  395.                 self.close()
  396.                 continue
  397.         
  398.  
  399.     
  400.     def collect_incoming_data(self, data):
  401.         '''Asynchat override.'''
  402.         self._request = self._request + data
  403.  
  404.     
  405.     def found_terminator(self):
  406.         '''Asynchat override.'''
  407.         (requestLine, headers) = (self._request + '\r\n').split('\r\n', 1)
  408.         
  409.         try:
  410.             (method, url, version) = requestLine.strip().split()
  411.         except ValueError:
  412.             self.writeError(400, "Malformed request: '%s'" % requestLine)
  413.             self.close_when_done()
  414.             return None
  415.  
  416.         method = method.upper()
  417.         (unused, unused, path, unused, query, unused) = urlparse.urlparse(url)
  418.         cgiParams = cgi.parse_qs(query, keep_blank_values = True)
  419.         if self.get_terminator() == '\r\n\r\n' and method == 'POST':
  420.             match = re.search('(?i)content-length:\\s*(\\d+)', headers)
  421.             contentLength = int(match.group(1))
  422.             if contentLength > 0:
  423.                 self.set_terminator(contentLength)
  424.                 self._request = self._request + '\r\n\r\n'
  425.                 return None
  426.             
  427.         
  428.         if type(self.get_terminator()) is type(1):
  429.             self.set_terminator('\r\n\r\n')
  430.             body = self._request.split('\r\n\r\n', 1)[1]
  431.             match = re.search('(?i)content-type:\\s*([^\\r\\n]+)', headers)
  432.             contentTypeHeader = match.group(1)
  433.             (contentType, pdict) = cgi.parse_header(contentTypeHeader)
  434.             if contentType == 'multipart/form-data':
  435.                 bodyFile = StringIO.StringIO(body)
  436.                 cgiParams.update(cgi.parse_multipart(bodyFile, pdict))
  437.             else:
  438.                 cgiParams.update(cgi.parse_qs(body, keep_blank_values = True))
  439.         
  440.         params = { }
  441.         for name, value in cgiParams.iteritems():
  442.             params[name] = value[0]
  443.         
  444.         headersRegex = re.compile('([^:]*):\\s*(.*)')
  445.         headersDict = [](_[1])
  446.         serverAuthMode = self._server.requestAuthenticationMode()
  447.         if serverAuthMode != HTTPServer.NO_AUTHENTICATION:
  448.             authResult = False
  449.             authHeader = headersDict.get('Authorization')
  450.             if authHeader:
  451.                 authMatch = re.search('(\\w+)\\s+(.*)', authHeader)
  452.                 (authenticationMode, login) = authMatch.groups()
  453.                 if authenticationMode == HTTPServer.BASIC_AUTHENTICATION:
  454.                     authResult = self._basicAuthentication(login)
  455.                 elif authenticationMode == HTTPServer.DIGEST_AUTHENTICATION:
  456.                     authResult = self._digestAuthentication(login, method)
  457.                 else:
  458.                     print >>sys.stdout, 'Unknown mode: %s' % authenticationMode
  459.             
  460.             if not authResult:
  461.                 self.writeUnauthorizedAccess(serverAuthMode)
  462.             
  463.         
  464.         if path == '/':
  465.             path = '/Home'
  466.         
  467.         pieces = path[1:].split('.')
  468.         name = [] + []([ piece.capitalize() for piece in pieces ])
  469.         for plugin in self._server._plugins:
  470.             if hasattr(plugin, name):
  471.                 plugin._handler = self
  472.                 
  473.                 try:
  474.                     getattr(plugin, name)(**params)
  475.                     if self._bufferedHeaders:
  476.                         self.write(None)
  477.                 except:
  478.                     ''.join
  479.                     'on'
  480.                     (eType, eValue, eTrace) = sys.exc_info()
  481.                     if eType == SystemExit:
  482.                         contextMap = self._context._map
  483.                         for dispatcher in contextMap.values():
  484.                             if isinstance(dispatcher, Listener):
  485.                                 dispatcher.close()
  486.                                 continue
  487.                         
  488.                         
  489.                         def isProtected(dispatcher):
  490.                             return not isinstance(dispatcher, _HTTPHandler)
  491.  
  492.                         while len(filter(isProtected, contextMap.values())) > 0:
  493.                             asyncore.poll(timeout = 1, map = contextMap)
  494.                         raise SystemExit
  495.                     
  496.                     message = '<h3>500 Server error</h3><pre>%s</pre>'
  497.                     details = traceback.format_exception(eType, eValue, eTrace)
  498.                     details = '\n'.join(details)
  499.                     self.writeError(500, message % cgi.escape(details))
  500.  
  501.                 plugin._handler = None
  502.                 break
  503.                 continue
  504.             ''.join
  505.         
  506.         self.close_when_done()
  507.  
  508.     
  509.     def onUnknown(self, path, params):
  510.         '''Handler for unknown URLs.  Returns a 404 page.'''
  511.         self.writeError(404, "Not found: '%s'" % path)
  512.  
  513.     
  514.     def writeOKHeaders(self, contentType, extraHeaders = { }):
  515.         '''Reflected from `HTTPPlugin`s.'''
  516.         timeNow = time.gmtime(time.time())
  517.         httpNow = time.strftime('%a, %d %b %Y %H:%M:%S GMT', timeNow)
  518.         headers = []
  519.         headers.append('HTTP/1.1 200 OK')
  520.         headers.append('Connection: close')
  521.         headers.append('Content-Type: %s' % contentType)
  522.         headers.append('Date: %s' % httpNow)
  523.         for name, value in extraHeaders.items():
  524.             headers.append('%s: %s' % (name, value))
  525.         
  526.         headers.append('')
  527.         headers.append('')
  528.         self._bufferedHeaders = headers
  529.  
  530.     
  531.     def writeError(self, code, message):
  532.         '''Reflected from `HTTPPlugin`s.'''
  533.         headers = []
  534.         if not self._headersWritten:
  535.             headers.append('HTTP/1.0 %d Error' % code)
  536.             headers.append('Connection: close')
  537.             headers.append('Content-Type: text/html')
  538.             headers.append('')
  539.             headers.append('')
  540.         
  541.         self.push('%s<html><body>%s</body></html>' % ('\r\n'.join(headers), message))
  542.  
  543.     
  544.     def write(self, content):
  545.         '''Reflected from `HTTPPlugin`s.'''
  546.         headers = []
  547.         if self._bufferedHeaders:
  548.             headers = self._bufferedHeaders
  549.             self._bufferedHeaders = None
  550.             self._headersWritten = True
  551.         
  552.         if content is None:
  553.             content = ''
  554.         
  555.         self.push('\r\n'.join(headers) + str(content))
  556.  
  557.     
  558.     def writeUnauthorizedAccess(self, authenticationMode):
  559.         '''Access is protected by HTTP authentication.'''
  560.         if authenticationMode == HTTPServer.BASIC_AUTHENTICATION:
  561.             authString = self._getBasicAuthString()
  562.         elif authenticationMode == HTTPServer.DIGEST_AUTHENTICATION:
  563.             authString = self._getDigestAuthString()
  564.         else:
  565.             self.writeError(500, 'Inconsistent authentication mode.')
  566.             return None
  567.         headers = []
  568.         headers.append('HTTP/1.0 401 Unauthorized')
  569.         headers.append('WWW-Authenticate: ' + authString)
  570.         headers.append('Connection: close')
  571.         headers.append('Content-Type: text/html')
  572.         headers.append('')
  573.         headers.append('')
  574.         self.write('\r\n'.join(headers) + self._server.getCancelMessage())
  575.         self.close_when_done()
  576.  
  577.     
  578.     def _getDigestAuthString(self):
  579.         '''Builds the WWW-Authenticate header for Digest authentication.'''
  580.         authString = 'Digest realm="' + self._server.getRealm() + '"'
  581.         authString += ', nonce="' + self._getCurrentNonce() + '"'
  582.         authString += ', opaque="0000000000000000"'
  583.         authString += ', stale="false"'
  584.         authString += ', algorithm="MD5"'
  585.         authString += ', qop="auth"'
  586.         return authString
  587.  
  588.     
  589.     def _getBasicAuthString(self):
  590.         '''Builds the WWW-Authenticate header for Basic authentication.'''
  591.         return 'Basic realm="' + self._server.getRealm() + '"'
  592.  
  593.     
  594.     def _getCurrentNonce(self):
  595.         '''Returns the current nonce value. This value is a Base64 encoding
  596.         of current time plus 20 minutes. This means the nonce will expire 20
  597.         minutes from now.'''
  598.         timeString = time.asctime(time.localtime(time.time() + 20 * 60))
  599.         if RSTRIP_CHARS_AVAILABLE:
  600.             return base64.encodestring(timeString).rstrip('\n=')
  601.         else:
  602.             
  603.             def rstrip(s, chars):
  604.                 if not s:
  605.                     return s
  606.                 
  607.                 if s[-1] in chars:
  608.                     return rstrip(s[:-1])
  609.                 
  610.                 return s
  611.  
  612.             return rstrip(base64.encodestring(timeString), '\n=')
  613.  
  614.     
  615.     def _isValidNonce(self, nonce):
  616.         '''Check if the specified nonce is still valid. A nonce is invalid
  617.         when its time converted value is lower than current time.'''
  618.         padAmount = len(nonce) % 4
  619.         if padAmount > 0:
  620.             padAmount = 4 - padAmount
  621.         
  622.         nonce += '=' * (len(nonce) + padAmount)
  623.         decoded = base64.decodestring(nonce)
  624.         return time.time() < time.mktime(time.strptime(decoded))
  625.  
  626.     
  627.     def _basicAuthentication(self, login):
  628.         '''Performs a Basic HTTP authentication. Returns True when the user
  629.         has logged in successfully, False otherwise.'''
  630.         (userName, password) = base64.decodestring(login).split(':')
  631.         return self._server.isValidUser(userName, password)
  632.  
  633.     
  634.     def _digestAuthentication(self, login, method):
  635.         '''Performs a Digest HTTP authentication. Returns True when the user
  636.         has logged in successfully, False otherwise.'''
  637.         
  638.         def stripQuotes(s):
  639.             if not s[0] == '"' or s[-1] == '"' or s[1:-1]:
  640.                 pass
  641.             return s
  642.  
  643.         options = dict(self._login_splitter.findall(login))
  644.         userName = stripQuotes(options['username'])
  645.         password = self._server.getPasswordForUser(userName)
  646.         nonce = stripQuotes(options['nonce'])
  647.         A1 = '%s:%s:%s' % (userName, self._server.getRealm(), password)
  648.         HA1 = md5.new(A1).hexdigest()
  649.         A2 = '%s:%s' % (method, stripQuotes(options['uri']))
  650.         HA2 = md5.new(A2).hexdigest()
  651.         unhashedDigest = ''
  652.         if options.has_key('qop'):
  653.             if not options['nc']:
  654.                 options['nc'] = '00000001'
  655.             
  656.             if not options['qop']:
  657.                 options['qop'] = 'auth'
  658.             
  659.             unhashedDigest = '%s:%s:%s:%s:%s:%s' % (HA1, nonce, stripQuotes(options['nc']), stripQuotes(options['cnonce']), stripQuotes(options['qop']), HA2)
  660.         else:
  661.             unhashedDigest = '%s:%s:%s' % (HA1, nonce, HA2)
  662.         hashedDigest = md5.new(unhashedDigest).hexdigest()
  663.         if stripQuotes(options['response']) == hashedDigest:
  664.             pass
  665.         return self._isValidNonce(nonce)
  666.  
  667.  
  668.  
  669. class HTTPPlugin:
  670.     '''Base class for HTTP server plugins.  See the main documentation for
  671.     details.'''
  672.     
  673.     def __init__(self):
  674.         pass
  675.  
  676.     
  677.     def onIncomingConnection(self, clientSocket):
  678.         '''Implement this and return False to veto incoming connections.'''
  679.         return True
  680.  
  681.     
  682.     def writeOKHeaders(self, contentType, extraHeaders = { }):
  683.         '''A methlet should call this with the Content-Type and optionally
  684.         a dictionary of extra headers (eg. Expires) before calling
  685.         `write()`.'''
  686.         return self._handler.writeOKHeaders(contentType, extraHeaders)
  687.  
  688.     
  689.     def writeError(self, code, message):
  690.         '''A methlet should call this instead of `writeOKHeaders()` /
  691.         `write()` to report an HTTP error (eg. 403 Forbidden).'''
  692.         return self._handler.writeError(code, message)
  693.  
  694.     
  695.     def write(self, content):
  696.         """A methlet should call this after `writeOKHeaders` to write the
  697.         page's content."""
  698.         return self._handler.write(content)
  699.  
  700.     
  701.     def flush(self):
  702.         '''A methlet can call this after calling `write`, to ensure that
  703.         the content is written immediately to the browser.  This isn\'t
  704.         necessary most of the time, but if you\'re writing "Please wait..."
  705.         before performing a long operation, calling `flush()` is a good
  706.         idea.'''
  707.         return self._handler.flush()
  708.  
  709.     
  710.     def close(self, flush = True):
  711.         """Closes the connection to the browser.  You should call `close()`
  712.         before calling `sys.exit()` in any 'shutdown' methlets you write."""
  713.         if flush:
  714.             self.flush()
  715.         
  716.         return self._handler.close()
  717.  
  718.  
  719.  
  720. def run(launchBrowser = False, context = _defaultContext):
  721.     '''Runs a `Dibbler` application.  Servers listen for incoming connections
  722.     and route requests through to plugins until a plugin calls `sys.exit()`
  723.     or raises a `SystemExit` exception.'''
  724.     if launchBrowser:
  725.         
  726.         try:
  727.             url = 'http://localhost:%d/' % context._HTTPPort
  728.             webbrowser.open_new(url)
  729.         except webbrowser.Error:
  730.             e = None
  731.             print '\n%s.\nPlease point your web browser at %s.' % (e, url)
  732.         except:
  733.             None<EXCEPTION MATCH>webbrowser.Error
  734.         
  735.  
  736.     None<EXCEPTION MATCH>webbrowser.Error
  737.     asyncore.loop(map = context._map)
  738.  
  739.  
  740. def runTestServer(readyEvent = None):
  741.     '''Runs the calendar server example, with an added `/shutdown` URL.'''
  742.     import Dibbler
  743.     import calendar
  744.     
  745.     class Calendar(Dibbler.HTTPPlugin):
  746.         _form = "<html><body><h3>Calendar Server</h3>\n                   <form action='/'>\n                   Year: <input type='text' name='year' size='4'>\n                   <input type='submit' value='Go'></form>\n                   <pre>%s</pre></body></html>"
  747.         
  748.         def onHome(self, year = None):
  749.             if year:
  750.                 result = calendar.calendar(int(year))
  751.             else:
  752.                 result = ''
  753.             self.writeOKHeaders('text/html')
  754.             self.write(self._form % result)
  755.  
  756.         
  757.         def onShutdown(self):
  758.             self.writeOKHeaders('text/html')
  759.             self.write('<html><body><p>OK.</p></body></html>')
  760.             self.close()
  761.             sys.exit()
  762.  
  763.  
  764.     httpServer = Dibbler.HTTPServer(8888)
  765.     httpServer.register(Calendar())
  766.     if readyEvent:
  767.         readyEvent.set()
  768.     
  769.     Dibbler.run(launchBrowser = True)
  770.  
  771.  
  772. def test():
  773.     '''Run a self-test.'''
  774.     import threading
  775.     import urllib
  776.     testServerReady = threading.Event()
  777.     threading.Thread(target = runTestServer, args = (testServerReady,)).start()
  778.     testServerReady.wait()
  779.     page = urllib.urlopen('http://localhost:8888/?year=2003').read()
  780.     if page.find('January') != -1:
  781.         print 'Self test passed.'
  782.     else:
  783.         print 'Self-test failed!'
  784.     raw_input('Press any key to shut down the application server...')
  785.     page = urllib.urlopen('http://localhost:8888/shutdown').read()
  786.     if page.find('OK') != -1:
  787.         print 'Shutdown OK.'
  788.     else:
  789.         print 'Shutdown failed!'
  790.  
  791. if __name__ == '__main__':
  792.     test()
  793.  
  794.